package heven.holt.library.widget.rise

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class RiseNumberTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.editTextStyle
) : AppCompatTextView(context, attrs, defStyleAttr), IRaiseNumber {

    companion object {
        const val STATE_STOPPED = 0
        const val STATE_RUNNING = 1
    }

    private var mPlayingState = STATE_STOPPED
    private var fromNum = 0f
    private var toNum = 0f
    private var duration = 1500L
    private var numberType = 2
    private var mEndListener: (() -> Unit)? = null


    fun isRunning() = mPlayingState == STATE_RUNNING

    private fun runFloat() {
        val valueAnimator = ValueAnimator.ofFloat(fromNum, toNum)
        valueAnimator.duration = duration
        valueAnimator.addUpdateListener {
            text = it.animatedValue.toString()
            if (valueAnimator.animatedFraction >= 1) {
                mEndListener?.invoke()
            }
        }
        valueAnimator.start()
    }

    private fun runInt() {
        val valueAnimator = ValueAnimator.ofInt(fromNum.toInt(), toNum.toInt())
        valueAnimator.duration = duration
        valueAnimator.addUpdateListener {
            text = it.animatedValue.toString()
            if (valueAnimator.animatedFraction >= 1) {
                mEndListener?.invoke()
            }
        }
        valueAnimator.start()
    }


    override fun start() {
        if (toNum == 0f) {
            text = fromNum.toInt().toString()
            return
        }
        if (!isRunning()) {
            mPlayingState = STATE_RUNNING
            if (numberType == 1)
                runInt()
            else
                runFloat()
        }
    }

    override fun setFloat(fromNum: Float, toNum: Float) {
        this.fromNum = fromNum
        this.toNum = toNum
        numberType = 2
    }

    override fun setInteger(fromNum: Int, toNum: Int) {
        this.fromNum = fromNum.toFloat()
        this.toNum = toNum.toFloat()
        numberType = 1
    }

    override fun setDuration(duration: Long) {
        this.duration = duration
    }

    override fun setOnEndListener(callback: () -> Unit) {
        this.mEndListener = callback
    }

}